/*
** StockDB
**
** Copyright (C) 2012 - ? doublegsoft
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <string.h>
#include <stdlib.h>

#include "protocol.h"

int
stockdb_protocol_header(const char *data, size_t size)
{
  int i = 0;
  char *header = PROTOCOL_HEADER;
  int len = strlen(header);
  if (len > size)
    return (-1);
  for (i = 0; i < len; i++)
  {
    if (data[i] != header[i])
      return (-1);
  }
  return (0);
}

int
stockdb_protocol_footer(const char *data, size_t size)
{
  int i = 0, j = 0;
  char *footer = PROTOCOL_FOOTER;
  int len = strlen(footer);
  if (len > size)
    return (-1);
  for (i = 0; i < size; i++)
  {
    if (data[i] == footer[j])
    {
      j++;
    }
    else
    {
      j = 0;
    }
    if (j == len)
      return (i - len);
  }
  return (-1);
}

const char *
stockdb_protocol_data(const char *data, int end)
{
  int len = sizeof(PROTOCOL_HEADER);
  int size = end - len + 1, i = len - 1, j = 0;
  char *ret = malloc(size);
  memset(ret, 0, size);
  for (; i < size + len; i++)
  {
    switch (data[i])
    {
    case '\0':
    case '\r':
    case '\n':
      break;
    default:
      ret[j++] = data[i];
      break;
    }
  }
  ret[j] = '\0';
  return (ret);
}
